package scau.erps.view.base;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import scau.erps.app.Erps;
import scau.erps.entity.Sand;
import scau.erps.entity.TeamOrder;
import scau.erps.service.SandService;
import scau.erps.service.TeamOrderService;
import scau.erps.service.impl.SandServiceImpl;
import scau.erps.service.impl.TeamOrderServiceImpl;
import scau.erps.util.CalculateQuarter;

/**
 * 贴现对话框
 * @author ZJC
 *
 */
public class DiscountDialog extends JDialog {
	private static final long serialVersionUID = 1L;
	int total1=0,total2=0,total3=0,total4=0;
	private final JPanel contentPanel = new JPanel();
	private SandService sandService=Erps.getIocInstance().get(SandServiceImpl.class);
	private DecisionPanel decisionPanel;
	private int team_Id = Erps.getCurrentTeam().getId();
	private JComboBox<String> timeComboBox;
	private JButton okButton =new JButton("确定");
	private int tie;
	
	public DiscountDialog(final DecisionPanel decisionPanel) {
		this.decisionPanel=decisionPanel;
		setModal(true);
		setTitle("贴现");
		setSize( 350, 250);
		setLocationRelativeTo(null);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		JLabel Label1 = new JLabel("选择应收账款");
		Label1.setBounds(20, 20, 100, 30);
		contentPanel.add(Label1);		
		JLabel Label2 = new JLabel("申请贴现金额");
		Label2.setBounds(20, 80, 100, 30);
		contentPanel.add(Label2);		
		 this.timeComboBox =new JComboBox<String>();
		this.getComboBoxItem();
		timeComboBox.setBounds(130, 20, 150, 30);
		contentPanel.add(timeComboBox);		
		final JTextField amountTextField = new JTextField();
		amountTextField.setBounds(130, 80, 150, 30);
		contentPanel.add(amountTextField);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
					okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						int timeSelected=0;
	
						if(timeComboBox.getSelectedItem()!=null)
						 timeSelected=Integer.parseInt(String.valueOf(timeComboBox.getSelectedItem().toString().charAt(0)));	
						Sand sand = sandService.getSandByTeam(team_Id);
						TeamOrderService teamOrderService = Erps.getIocInstance().get(TeamOrderServiceImpl.class);
						List<TeamOrder> list = teamOrderService.getTeamOrderByStatus(team_Id, "已交货");
						
						int amount=0,quarter=0;
						  try  
						  {
						       amount=Integer.parseInt(amountTextField.getText());
                               if(amount<=0||amount%10!=0)throw new Exception("不是10的倍数");//判断输入是否为10的倍数
                               //判断小组的当前操作步骤在应收款更新步骤的前还是后，以便来算账期 ,更新应收款前后的账期要区别。如此时是YOQ1，订单收钱时间是Y0Q1.还没到应收款收现的时候，你便贴现的话，这里还是是存在1Q的账期的
                            	  switch(timeSelected){
                            	  case 1:if(total1<amount)throw new Exception("1Q应账期的应收款不足"); break;
                            	  case 2:if(total2<amount)throw new Exception("2Q应账期的应收款不足"); break;
                            	  case 3:if(total3<amount)throw new Exception("3Q应账期的应收款不足"); break;
                            	  case 4:if(total4<amount)throw new Exception("4Q应账期的应收款不足"); break;
                            	  default: throw new Exception("找不到账期");
                            	  }
                               {
                            	   //更新sand的cash和discount账期为1或2贴息为10%  ，账期为3或4的贴息为20% 
                            	   int discount;
                            	   int cash=sand.getCash();        	   
                            	     if(timeSelected==1||timeSelected==2){
                            	    	 cash=cash+(int)(amount*0.9);
                            	    	 discount=(int)(amount*0.1);
                            	     }
                            	     else{
                            	    	 cash=cash+(int)(amount*0.8);
                            	    	  discount=(int)(amount*0.2);
                            	     }
                            	     sand.setCash(cash);
                            	     sand.setDiscount(sand.getDiscount()+discount);
                            	     sandService.updateSand(sand);
                       
                            		for (TeamOrder teamOrder : list) {
                            			//找到对应账期的订单tie进行更新
                            			if(teamOrder.getTie()==(0)){
                            				tie=teamOrder.getTotal()-teamOrder.getPenalty();
                            			}
                            			else{
                            				tie=teamOrder.getTie();
                            			}
                            			if(Integer.parseInt(sand.getStep())>=21){
                            				quarter=CalculateQuarter.getQuarter(teamOrder.getReceivable(),sand.getTime());
                            				}
                            			else quarter=CalculateQuarter.getQuarter(teamOrder.getReceivable(),sand.getTime())+1;
                            			if(timeSelected==quarter){
                            			amount=amount-tie;
            							if(amount>0)
            							{
            								teamOrder.setTie(-1);
            								teamOrder.setStatus("已贴息");
            								teamOrderService.updateTeamOrder(teamOrder);   
            							}
            							else if(amount==0){
            								teamOrder.setTie(-1);
            								teamOrder.setStatus("已贴息");
            								teamOrderService.updateTeamOrder(teamOrder);  
            								break;
            							}
            							else if(amount<0){//数学运算得来的penalty-amount;
            								teamOrder.setTie(-amount);
            								teamOrderService.updateTeamOrder(teamOrder);
            								break;
            							}
            						}
                            		}
                            		String message="成功贴现一笔额度为"+amountTextField.getText()+"账期为"+quarter+"Q的贴现金额";
            						JOptionPane.showMessageDialog(null, message, "提醒",JOptionPane.INFORMATION_MESSAGE);
            						//更新下拉框内容
            						timeComboBox.removeAllItems();
            						getComboBoxItem();
            						
                               }
                               //更新界面
                            decisionPanel.getDashBoardPanel().setDashBoardData(21);
                            decisionPanel.getDashBoardPanel().setReceivableData();
						  }
						  catch(Exception e)
						  {
							  JOptionPane.showMessageDialog(null, "请检查输入内容是否为输入大于零且为10的倍数的整数或者应收款是否足够", "提醒",JOptionPane.INFORMATION_MESSAGE);
						  }
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton exitButton = new JButton("取消");
				exitButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
                          dispose();
					}
				});
				exitButton.setActionCommand("Cancel");
				buttonPane.add(exitButton);
			}
		}
		setVisible(true);
	}
	public void getComboBoxItem (){
		String quarter1="",quarter2="",quarter3="",quarter4="";
		int quarter;
		int temptie;total1=0;total2=0;total3=0;total4=0;
		Sand sand = sandService.getSandByTeam(team_Id);
		TeamOrderService teamOrderService = Erps.getIocInstance().get(TeamOrderServiceImpl.class);
		List<TeamOrder> list = teamOrderService.getTeamOrderByStatus(team_Id, "已交货");
		for(TeamOrder teamOrder:list){
			if(teamOrder.getTie()==0){
				temptie=teamOrder.getTotal()-teamOrder.getPenalty();
			}
			else{
				temptie=teamOrder.getTie();
			}

			if(Integer.parseInt(sand.getStep())>=21){
				quarter=CalculateQuarter.getQuarter(teamOrder.getReceivable(),sand.getTime());
				switch (quarter){
				case 1:total1=total1+temptie;break;
				case 2:total2=total2+temptie;break;
				case 3:total3=total3+temptie;break;
				case 4:total4=total4+temptie;break;
				default: System.out.print("贴现账期计算错误");
				}
			}
			else{
				quarter=CalculateQuarter.getQuarter(teamOrder.getReceivable(),sand.getTime());
				switch (quarter){
				case 0:total1=total1+temptie;break;
				case 1:total2=total2+temptie;break;
				case 2:total3=total3+temptie;break;
				case 3:total4=total4+temptie;break;
				default: System.out.print("贴现账期计算错误");
				}
			}	
		}	
		if(total1<10 && total2<10 && total3<10 && total4<10){
			timeComboBox.addItem("没有大于10M应收款");
			okButton.setEnabled(false);
			
		}else{
			if(total1>=10) {quarter1="1Q可贴现"+total1;timeComboBox.addItem(quarter1);}
			if(total2>=10) {quarter2="2Q可贴现"+total2;timeComboBox.addItem(quarter2);}
			if(total3>=10) {quarter3="3Q可贴现"+total3;timeComboBox.addItem(quarter3);}
			if(total4>=10) {quarter4="4Q可贴现"+total4;timeComboBox.addItem(quarter4);}
		}
		
	}
}
